package fast;

import java.io.*;
import java.net.*;

/**
 * TCPListener Class
 * 
 * Provides a TCP socket listening on a port, any connections made to this port
 * will have their data written to a buffer. Must be run as a thread.
 * 
 * @version 0.1
 * @author Adam Bell
 * @date 17/12/2009
 */
public class TCPListener implements Runnable {
	private int port;
	private Buffer listenBuffer;
	private ServerSocket ss;

	/**
	 * Constructor
	 * 
	 * @param port
	 *            The port to listen on
	 * @param listenBuffer
	 *            The buffer to add entries to
	 */
	public TCPListener(int port, Buffer listenBuffer) {
		this.port = port;
		this.listenBuffer = listenBuffer;
	}

	/**
	 * Thread actions.
	 */
	public void run() {
		// create a listening socket
		ss = null;
		try {
			ss = new ServerSocket(port);
		} catch (IOException e) {
			e.printStackTrace();
		}

		// keep adding packets to the listen buffer
		while (true) {
			try {
				// actions when client connects
				Socket clientSocket = null;
				clientSocket = ss.accept();

				// grab the buffered inputstream
				BufferedInputStream bin = new BufferedInputStream(clientSocket
						.getInputStream());

				// TODO: suitable byte array size
				byte[] dataIn = new byte[200];

				// grab data to byte array
				bin.read(dataIn);

				// convert to string, add to listenBuffer
				// trim off a leading character, otherwise a '/' gets prepended
				// to the address
				listenBuffer.add(clientSocket.getInetAddress().toString()
						.substring(1)
						+ "|" + new String(dataIn).trim());

			} catch (IOException e) {
				System.out.print(e);
			} catch (InterruptedException e) {
				System.out.print(e);
			}// try
		}// while
	}// run()
}
